package com.sl.au.interceptor;

import com.sl.au.entity.Account;
import com.sl.au.entity.Module;
import com.sl.au.entity.Role;
import com.sl.au.repository.AccountRepository;
import com.sl.au.service.ModuleService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLDecoder;
public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private AccountRepository accountRepository;
	@Autowired
	private ModuleService moduleService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		/**
		 * 用于移动端
		 */
		String mobile =request.getParameter("device");
		String identify =request.getParameter("identify");
		
		
		// 移动端暂时放行
		/*String device = request.getHeader("device");
		if (StringUtils.hasText(device) && device.equals("mobile"))
			return true;*/

		String URL = request.getRequestURI().toString();

		//接口放行
		if(URL.contains("eventReportOuter")){
			return true;
		}

		if(URL.contains("deleteExde")){
			return true;
		}

		if(URL.contains("setUserTrajectory") || URL.contains("getOnlineUser")){
			return true;
		}
		
		String crmout = request.getHeader("crm-out");
		String outkey = "D9A61EBF-4CC6-4E49-9561-58A6E34F34DF";
		String userid = request.getHeader("userid");
		if (StringUtils.hasText(crmout) && crmout.equals(outkey) && StringUtils.hasText(userid)) return true;
		
		
		if (URL.contains("/crmout/") || URL.contains("/json") || URL.contains("loginmessage"))
			return true;
		
		Account account = (Account) request.getSession().getAttribute("account");
		
		//临时添加
		String showUser =request.getParameter("showUser");
		if(account==null&&StringUtils.hasText(showUser)){
			if(this.accountRepository==null)
			{
				BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
				accountRepository = (AccountRepository) factory.getBean("accountRepository"); 
			}
			account =this.accountRepository.findByAccountName(showUser);

			if(this.moduleService == null){
				BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
				moduleService = (ModuleService) factory.getBean("ModuleService");
			}
			if(account != null){
				// 获取角色权限
				Role role = account.getRole();
				role.setModuleInfos(moduleService.getModulesInfo(role));
				request.getSession().setAttribute("account",account);
			}

			
			/*request.getRequestDispatcher(URL.replace("/wcsi", "")).forward(request, response);
			return true;*/
		}
		
		if(account==null&&StringUtils.hasText(mobile) && mobile.equals("mobile")){//&& StringUtils.hasText(identify)
			
			if(this.accountRepository==null)
			{
				BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
				accountRepository = (AccountRepository) factory.getBean("accountRepository"); 
			}
			// 读取浏览器cookie，并验证是否满足用户登录需求
						Cookie[] cookies = request.getCookies();
						String uid = "";
						String pwd = "";
						if (null != cookies) {
							for (Cookie cookie : cookies) {
								if (cookie.getName().equals("dcodeuid")) {
									uid = URLDecoder.decode(cookie.getValue(),"utf-8");
								} else if (cookie.getName().equals("dcodeupwd")) {
									pwd = URLDecoder.decode(cookie.getValue(),"utf-8");
								}
							}
						}
						account = this.accountRepository.findByAccountNameOrPhoneNumberAndPassword(uid, pwd);
						if(account==null){
							account =this.accountRepository.findByAccountName("Visitors");				
						}
			
			request.getSession().setAttribute("account",account);
		}
		
		String contextPath = request.getContextPath();

		if (StringUtils.hasText(contextPath) && URL.startsWith(contextPath)) {
			URL = URL.substring(contextPath.length());
		}
		/*// 首页允许
		if (URL.equals("/ui/index") || URL.contains("/index/")) {
			return true;
		}*/
		// 登录页允许
		if (URL.endsWith("login")||URL.endsWith("login/submit")||URL.endsWith("login/msubmit")||URL.endsWith("login/reset")) {
			//request.getSession().removeAttribute("account");
			//request.getSession().invalidate();
			return true;
		}
		// 注册允许
		if (URL.endsWith("register")||URL.endsWith("registerUser")||URL.contains("/mobileMain/sendCodeByPhone/")) {
			return true;
		}
		// 下载app允许
		if (URL.endsWith("download") || URL.endsWith("downapk") || URL.endsWith("getVersion")) {
			return true;
		}

		// 大屏幕显示
		if (URL.indexOf("screen") > -1) {
			return true;
		}

		// session中没有账号的情况
		if (account == null && !URL.endsWith("login/submit")) {
			if(mobile==null||!mobile.equals("mobile")){
			// response.sendRedirect(contextPath + "/ui/login");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print("<script type='text/javascript'>alert('禁止未登录用户访问'); window.location.href='"
					+ request.getContextPath() + "/ui/login';</script>");
			out.flush();
			out.close();
			
			return false;
		}else{
				/*// 做无浏览权限验证，或者未登陆用户，转发到登陆页面
	            session.setAttribute(Constants.Session.ACCOUNT_ATTRIBUTE_NAME,
	                    null);
	            request.getRequestDispatcher("/login.jsp").forward(
	                    request, response);
	            return false;*/
				String queryurl=request.getQueryString();  
			    if(null!=queryurl){
			    		URL+="?"+queryurl;
			    }
//				request.getRequestDispatcher("/ui/login?device=mobile&&identify="+identify+"&&url="+URL).forward(request, response);
//			    response.sendRedirect(request.getContextPath()+"/ui/login?device=mobile&&identify="+identify+"&&url="+URL);
			    response.sendRedirect(request.getContextPath()+"/ui/login?device=mobile&&identify="+identify);
				return false;
			}
		}
		// 有账号要进行权限审核
		if (null != account) {
			Boolean isOwner = false;

			if (URL.contains("/index") 
					|| URL.contains("/task/") 
					|| URL.contains("/crmout/") || URL.contains("/a/")
					|| URL.contains("/getModulePage") || URL.contains("/getManagerPage") || URL.contains("/getStaff")
					|| URL.contains("/afterSaleOutHouse/get") || URL.contains("/afterSaleOutHouse/save") 
					|| URL.contains("/validUser") 	|| URL.contains("/inventoryReduce/get") 
					|| URL.contains("/chance/detail") ||URL.contains("/chanceTrance/")
					||URL.contains("/chanceKeyMan/")	||URL.contains("/quote/get")
					||URL.contains("/demo/")
					||URL.contains("/getmystarts/")
					||URL.contains("/managerDelivery/deleteUser")||URL.contains("/rejectSave")
					|| URL.contains("/distribute")|| URL.contains("/user/getpage")|| URL.contains("/contract/getDevice")
					|| URL.contains("/getContract")//合同列表全部通过 --20170511
					|| URL.contains("/configdetailfor")//引入二期报价单--20170518
					|| URL.contains("/ueditor")
					||URL.contains("/m2r")) {//百度编辑器Ueditor
				return true;
			}
			
			for (Module m : account.getRole().getModules()) {
				if (URL.contains(m.getTarget().replace("?device=mobile", ""))) {
					isOwner = true;
					break;
				}
				if (!m.getTarget().equals("#")) {
					String model = m.getTarget().split("/")[2];
					if(model.indexOf("?") != -1) {
						model = model.split("\\?")[0];
					}
					if (URL.contains(model))
						isOwner = true;
				}
			}
			if (!isOwner) {
				if(mobile==null||!mobile.equals("mobile")){
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				out.print("<script type='text/javascript'>alert('未授权访问'); window.history.go(-1);</script>");
				out.flush();
				out.close();
				}
				else{
					/*// 做无浏览权限验证，或者未登陆用户，转发到登陆页面
		            session.setAttribute(Constants.Session.ACCOUNT_ATTRIBUTE_NAME,
		                    null);
		            request.getRequestDispatcher("/login.jsp").forward(
		                    request, response);
		            return false;*/
					//request.getRequestDispatcher("/ui/login?device=mobile&&identify="+identify+"&&url="+URL).forward(request, response);
					 response.sendRedirect(request.getContextPath()+"/ui/login?device=mobile&&identify="+identify);
					return false;
				}

			}
			return isOwner;
		}
		return true;
	}
}
